package api

import (
	"fmt"
	"go-http/netdisk/common"
	"go-http/netdisk/conf"
	"go-http/netdisk/db"
	"go-http/netdisk/pkg/e"
	"go-http/netdisk/pkg/utils"
	"net/http"
	"os"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

type Pager struct {
	//当前页数，0基
	Page int `json:"page"`
	//每页的大小
	PageSize int `json:"pageSize"`
	//总的条目数
	TotalItems int `json:"totalItems"`
	//总的页数
	TotalPages int `json:"totalPages"`
	//实体的数组
	Data interface{} `json:"data"`
}

// type UploadFile struct {
// 	Uid     string //选填 用户的唯一标识，文件存放在该用户名下（uid和gid只能填一个）
// 	Gid     string //选填 组的唯一标识，文件存放在该组名下（uid和gid只能填一个）
// 	Pfid    string //选填 文件上传到哪个目录下
// 	File    file   //必填 二进制文件，在浏览器中是通过`<input type="file" name="file"/>`来选择的
// 	Alien   bool   //选填 是否为第三方文件，默认`false`
// 	Privacy bool   //选填 文件的私有性，默认`true`
// }

// 所有字段首字母必须大写
type File struct {
	Fid        string
	Filename   string
	Pfid       string
	Path       string
	IsDir      uint8 `gorm:"default:;"`
	CreateTime time.Time
	UpdateTime time.Time
	Uid        string
	Md5        string `gorm:"default:;"`
	Size       int64
	Permission uint8     `gorm:"default:;"`
	Deleted    uint8     `gorm:"default:;"`
	DeleteTime time.Time `gorm:"default:;"`
}

func GetPage(c *gin.Context) {
	// c.BindJSON()
	c.JSON(http.StatusOK, common.ResponseData{Code: e.SUCCESS, Msg: e.GetMsg(e.SUCCESS)})
	fmt.Println("Getpage success!!!")
}

func Upload(c *gin.Context) {
	uid := c.PostForm("uid")
	pfid := c.PostForm("pfid")
	alien := c.PostForm("alien")
	permissionStr := c.PostForm("permission")

	fmt.Printf("uid:%s, pfid:%s, alien:%s, permission:%s\n", uid, pfid, alien, permissionStr)

	if permissionStr == "0" || permissionStr == "1" || permissionStr == "2" {
		permission, _ := strconv.Atoi(permissionStr)

		if uid != "" {
			var u User
			if err := db.DB.Find(&u, "uid = ?", uid).Error; err != nil {
				// 用户不存在
				c.JSON(http.StatusBadRequest, gin.H{"msg": err.Error()})
			} else {
				var f File
				if pfid == "/" {
					f.Fid = "/"
					f.Path = ""
				} else {
					if err := db.DB.Find(&f, "pfid = ?", pfid).Error; err != nil {
						// 文件夹不存在
						c.JSON(http.StatusBadRequest, gin.H{"msg": err.Error()})
						return
					}
				}

				if file, err := c.FormFile("file"); err != nil {
					// 文件获取失败
					c.JSON(http.StatusOK, gin.H{"msg": err.Error()})
				} else {
					tm := time.Now()
					newFile := File{
						Fid:      utils.NewV4String(),
						Filename: file.Filename,
						Pfid:     f.Fid,
						Path:     f.Path + "/" + file.Filename,
						// IsDir      :0,
						CreateTime: tm,
						UpdateTime: tm,
						Uid:        uid,
						// Md5        :,
						Size:       file.Size,
						Permission: uint8(permission),
						// Deleted    :
						// DeleteTime :
					}

					if err := db.DB.Create(&newFile).Error; err != nil {
						// 数据库插入失败
						c.JSON(http.StatusInternalServerError, gin.H{"msg": err.Error()})
					} else {
						rootDir := conf.STORE_PATH + u.Username
						if _, err := os.Stat(rootDir); os.IsNotExist(err) {
							os.MkdirAll(rootDir, 0777)
						}

						if err := c.SaveUploadedFile(file, rootDir+newFile.Path); err != nil {
							// 文件保存失败
							c.JSON(http.StatusInternalServerError, gin.H{"msg": err.Error()})
						} else {
							c.JSON(http.StatusOK, gin.H{"msg": "file upload success"})
						}
					}
				}
			}
		} else {
			c.JSON(http.StatusBadRequest, gin.H{"msg": "uid is empty"})
		}
	} else {
		c.JSON(http.StatusBadRequest, gin.H{"msg": fmt.Sprintf("err, permission:%s", permissionStr)})
	}
}

func CreateDirectory(c *gin.Context) {

}
